home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / non-ANSI / c-client / imap2.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-06-19  |  64.3 KB  |  2,136 lines

  1. /*
  2.  * Program:    Interactive Mail Access Protocol 2 (IMAP2) routines
  3.  *
  4.  * Author:    Mark Crispin
  5.  *        Networks and Distributed Computing
  6.  *        Computing & Communications
  7.  *        University of Washington
  8.  *        Administration Building, AG-44
  9.  *        Seattle, WA  98195
  10.  *        Internet: MRC@CAC.Washington.EDU
  11.  *
  12.  * Date:    15 June 1988
  13.  * Last Edited:    19 June 1993
  14.  *
  15.  * Sponsorship:    The original version of this work was developed in the
  16.  *        Symbolic Systems Resources Group of the Knowledge Systems
  17.  *        Laboratory at Stanford University in 1987-88, and was funded
  18.  *        by the Biomedical Research Technology Program of the National
  19.  *        Institutes of Health under grant number RR-00785.
  20.  *
  21.  * Original version Copyright 1988 by The Leland Stanford Junior University
  22.  * Copyright 1993 by the University of Washington
  23.  *
  24.  *  Permission to use, copy, modify, and distribute this software and its
  25.  * documentation for any purpose and without fee is hereby granted, provided
  26.  * that the above copyright notices appear in all copies and that both the
  27.  * above copyright notices and this permission notice appear in supporting
  28.  * documentation, and that the name of the University of Washington or The
  29.  * Leland Stanford Junior University not be used in advertising or publicity
  30.  * pertaining to distribution of the software without specific, written prior
  31.  * permission.  This software is made available "as is", and
  32.  * THE UNIVERSITY OF WASHINGTON AND THE LELAND STANFORD JUNIOR UNIVERSITY
  33.  * DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD TO THIS SOFTWARE,
  34.  * INCLUDING WITHOUT LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  35.  * FITNESS FOR A PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE UNIVERSITY OF
  36.  * WASHINGTON OR THE LELAND STANFORD JUNIOR UNIVERSITY BE LIABLE FOR ANY
  37.  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
  38.  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
  39.  * CONTRACT, TORT (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF
  40.  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  41.  *
  42.  */
  43.  
  44.  
  45. #include <ctype.h>
  46. #include <stdio.h>
  47. #include "mail.h"
  48. #include "osdep.h"
  49. #include "imap2.h"
  50. #include "misc.h"
  51.  
  52. /* Driver dispatch used by MAIL */
  53.  
  54. DRIVER imapdriver = {
  55.   "imap2",            /* driver name */
  56.   (DRIVER *) NIL,        /* next driver */
  57.   map_valid,            /* mailbox is valid for us */
  58.   map_parameters,        /* manipulate parameters */
  59.   map_find,            /* find mailboxes */
  60.   map_find_bboards,        /* find bboards */
  61.   map_find_all,            /* find all mailboxes */
  62.   map_find_all_bboards,        /* find all bboards */
  63.   map_subscribe,        /* subscribe to mailbox */
  64.   map_unsubscribe,        /* unsubscribe from mailbox */
  65.   map_subscribe_bboard,        /* subscribe to bboard */
  66.   map_unsubscribe_bboard,    /* unsubscribe from bboard */
  67.   map_create,            /* create mailbox */
  68.   map_delete,            /* delete mailbox */
  69.   map_rename,            /* rename mailbox */
  70.   map_open,            /* open mailbox */
  71.   map_close,            /* close mailbox */
  72.   map_fetchfast,        /* fetch message "fast" attributes */
  73.   map_fetchflags,        /* fetch message flags */
  74.   map_fetchstructure,        /* fetch message envelopes */
  75.   map_fetchheader,        /* fetch message header only */
  76.   map_fetchtext,        /* fetch message body only */
  77.   map_fetchbody,        /* fetch message body section */
  78.   map_setflag,            /* set message flag */
  79.   map_clearflag,        /* clear message flag */
  80.   map_search,            /* search for message based on criteria */
  81.   map_ping,            /* ping mailbox to see if still alive */
  82.   map_check,            /* check for new messages */
  83.   map_expunge,            /* expunge deleted messages */
  84.   map_copy,            /* copy messages to another mailbox */
  85.   map_move,            /* move messages to another mailbox */
  86.   map_append,            /* append string message to mailbox */
  87.   map_gc            /* garbage collect stream */
  88. };
  89.  
  90.                 /* prototype stream */
  91. MAILSTREAM imapproto = {&imapdriver};
  92.  
  93.                 /* driver parameters */
  94. long map_maxlogintrials = MAXLOGINTRIALS;
  95. long map_lookahead = MAPLOOKAHEAD;
  96. long map_port = IMAPTCPPORT;
  97.  
  98. /* Mail Access Protocol validate mailbox
  99.  * Accepts: mailbox name
  100.  * Returns: our driver if name is valid, NIL otherwise
  101.  */
  102.  
  103. DRIVER *map_valid (name)
  104.     char *name;
  105. {
  106.   return mail_valid_net (name,&imapdriver,NIL,NIL);
  107. }
  108.  
  109.  
  110. /* Mail Access Protocol manipulate driver parameters
  111.  * Accepts: function code
  112.  *        function-dependent value
  113.  * Returns: function-dependent return value
  114.  */
  115.  
  116. void *map_parameters (function,value)
  117.     long function;
  118.     void *value;
  119. {
  120.   switch ((int) function) {
  121.   case SET_MAXLOGINTRIALS:
  122.     map_maxlogintrials = (long) value;
  123.   case GET_MAXLOGINTRIALS:
  124.     return (void *) map_maxlogintrials;
  125.   case SET_LOOKAHEAD:
  126.     map_lookahead = (long) value;
  127.   case GET_LOOKAHEAD:
  128.     return (void *) map_lookahead;
  129.   case SET_PORT:
  130.     map_port = (long) value;
  131.   case GET_PORT:
  132.     return (void *) map_port;
  133.   default:
  134.     break;
  135.   }
  136.   fatal ("Invalid map_parameters function");
  137. }
  138.  
  139. /* Mail Access Protocol find list of mailboxes
  140.  * Accepts: mail stream
  141.  *        pattern to search
  142.  */
  143.  
  144. void map_find (stream,pat)
  145.     MAILSTREAM *stream;
  146.     char *pat;
  147. {
  148.   void *s = NIL;
  149.   char *t,*bbd,*patx,tmp[MAILTMPLEN];
  150.   if (stream) {            /* have a mailbox stream open? */
  151.                 /* begin with a host specification? */
  152.     if (((*pat == '{') || ((*pat == '*') && (pat[1] == '{'))) &&
  153.     (t = strchr (pat,'}')) && *(patx = ++t)) {
  154.       if (*pat == '*') pat++;    /* yes, skip leading * (old Pine behavior) */
  155.       strcpy (tmp,pat);        /* copy host name */
  156.       tmp[patx-pat] = '\0';    /* tie off prefix */
  157.       LOCAL->prefix = cpystr (tmp);
  158.     }
  159.     else patx = pat;        /* use entire specification */
  160.     if (LOCAL && LOCAL->use_find &&
  161.     !strcmp (imap_send (stream,"FIND MAILBOXES",patx,NIL)->key,"BAD"))
  162.       LOCAL->use_find = NIL;    /* note no finding with this server */
  163.     if (LOCAL->prefix) fs_give ((void **) &LOCAL->prefix);
  164.   }
  165.   else while (t = sm_read (&s))    /* read subscription database */
  166.     if ((*t != '*') && mail_valid_net (t,&imapdriver,NIL,NIL) && pmatch(t,pat))
  167.       mm_mailbox (t);
  168. }
  169.  
  170. /* Mail Access Protocol find list of bboards
  171.  * Accepts: mail stream
  172.  *        pattern to search
  173.  */
  174.  
  175. void map_find_bboards (stream,pat)
  176.     MAILSTREAM *stream;
  177.     char *pat;
  178. {
  179.   void *s = NIL;
  180.   char *t,*bbd,*patx,tmp[MAILTMPLEN];
  181.   if (stream) {            /* have a mailbox stream open? */
  182.                 /* begin with a host specification? */
  183.     if (((*pat == '{') || ((*pat == '*') && (pat[1] == '{'))) &&
  184.     (t = strchr (pat,'}')) && *(patx = ++t)) {
  185.       if (*pat == '*') pat++;    /* yes, skip leading * (old Pine behavior) */
  186.       strcpy (tmp,pat);        /* copy host name */
  187.       tmp[patx-pat] = '\0';    /* tie off prefix */
  188.       LOCAL->prefix = cpystr (tmp);
  189.     }
  190.     else patx = pat;        /* use entire specification */
  191.                 /* this is optional, so no complaint if fail */
  192.     if (stream && LOCAL && LOCAL->use_find && LOCAL->use_bboard &&
  193.     !strcmp (imap_send (stream,"FIND BBOARDS",patx,NIL)->key,"BAD"))
  194.       LOCAL->use_bboard = NIL;
  195.     if (LOCAL->prefix) fs_give ((void **) &LOCAL->prefix);
  196.   }
  197.   else while (t = sm_read (&s))    /* read subscription database */
  198.     if ((*t == '*') && mail_valid_net (++t,&imapdriver,NIL,NIL) &&
  199.     pmatch (t,pat)) mm_bboard (t);
  200. }
  201.  
  202. /* Mail Access Protocol find list of all mailboxes
  203.  * Accepts: mail stream
  204.  *        pattern to search
  205.  */
  206.  
  207. void map_find_all (stream,pat)
  208.     MAILSTREAM *stream;
  209.     char *pat;
  210. {
  211.   char *t,*bbd,*patx,tmp[MAILTMPLEN];
  212.   if (stream) {            /* have a mailbox stream open? */
  213.                 /* begin with a host specification? */
  214.     if (((*pat == '{') || ((*pat == '*') && (pat[1] == '{'))) &&
  215.     (t = strchr (pat,'}')) && *(patx = ++t)) {
  216.       if (*pat == '*') pat++;    /* yes, skip leading * (old Pine behavior) */
  217.       strcpy (tmp,pat);        /* copy host name */
  218.       tmp[patx-pat] = '\0';    /* tie off prefix */
  219.       LOCAL->prefix = cpystr (tmp);
  220.     }
  221.     else patx = pat;        /* use entire specification */
  222.                 /* this is optional, so no complaint if fail */
  223.     if (LOCAL && LOCAL->use_find &&
  224.     !strcmp (imap_send (stream,"FIND ALL.MAILBOXES",patx,NIL)->key,"BAD")){
  225.       map_find (stream,pat);    /* perhaps older server */
  226.                 /* always include INBOX for consistency */
  227.       if (pmatch (pat,"INBOX")) mm_mailbox ("INBOX");
  228.     }
  229.     if (LOCAL->prefix) fs_give ((void **) &LOCAL->prefix);
  230.   }
  231. }
  232.  
  233.  
  234. /* Mail Access Protocol find list of all bboards
  235.  * Accepts: mail stream
  236.  *        pattern to search
  237.  */
  238.  
  239. void map_find_all_bboards (stream,pat)
  240.     MAILSTREAM *stream;
  241.     char *pat;
  242. {
  243.   char *t,*bbd,*patx,tmp[MAILTMPLEN];
  244.   if (stream) {            /* have a mailbox stream open? */
  245.                 /* begin with a host specification? */
  246.     if (((*pat == '{') || ((*pat == '*') && (pat[1] == '{'))) &&
  247.     (t = strchr (pat,'}')) && *(patx = ++t)) {
  248.       if (*pat == '*') pat++;    /* yes, skip leading * (old Pine behavior) */
  249.       strcpy (tmp,pat);        /* copy host name */
  250.       tmp[patx-pat] = '\0';    /* tie off prefix */
  251.       LOCAL->prefix = cpystr (tmp);
  252.     }
  253.     else patx = pat;        /* use entire specification */
  254.                 /* this is optional, so no complaint if fail */
  255.     if (LOCAL && LOCAL->use_find &&
  256.     !strcmp (imap_send (stream,"FIND ALL.BBOARDS",patx,NIL)->key,"BAD"))
  257.       map_find_bboards (stream,pat);
  258.     if (LOCAL->prefix) fs_give ((void **) &LOCAL->prefix);
  259.   }
  260. }
  261.  
  262. /* Mail Access Protocol subscribe to mailbox
  263.  * Accepts: mail stream
  264.  *        mailbox to add to subscription list
  265.  * Returns: T on success, NIL on failure
  266.  */
  267.  
  268. long map_subscribe (stream,mailbox)
  269.     MAILSTREAM *stream;
  270.     char *mailbox;
  271. {
  272.   return map_manage (stream,mailbox,"Subscribe Mailbox",NIL);
  273. }
  274.  
  275.  
  276. /* Mail access protocol unsubscribe to mailbox
  277.  * Accepts: mail stream
  278.  *        mailbox to delete from manage list
  279.  * Returns: T on success, NIL on failure
  280.  */
  281.  
  282. long map_unsubscribe (stream,mailbox)
  283.     MAILSTREAM *stream;
  284.     char *mailbox;
  285. {
  286.   return map_manage (stream,mailbox,"Unsubscribe Mailbox",NIL);
  287. }
  288.  
  289.  
  290. /* Mail Access Protocol subscribe to bboard
  291.  * Accepts: mail stream
  292.  *        mailbox to add to manage list
  293.  * Returns: T on success, NIL on failure
  294.  */
  295.  
  296. long map_subscribe_bboard (stream,mailbox)
  297.     MAILSTREAM *stream;
  298.     char *mailbox;
  299. {
  300.   return map_manage (stream,mailbox,"Subscribe BBoard",NIL);
  301. }
  302.  
  303.  
  304. /* Mail access protocol unsubscribe to bboard
  305.  * Accepts: mail stream
  306.  *        mailbox to delete from manage list
  307.  * Returns: T on success, NIL on failure
  308.  */
  309.  
  310. long map_unsubscribe_bboard (stream,mailbox)
  311.     MAILSTREAM *stream;
  312.     char *mailbox;
  313. {
  314.   return map_manage (stream,mailbox,"Unsubscribe BBoard",NIL);
  315. }
  316.  
  317. /* Mail Access Protocol create mailbox
  318.  * Accepts: mail stream
  319.  *        mailbox name to create
  320.  * Returns: T on success, NIL on failure
  321.  */
  322.  
  323. long map_create (stream,mailbox)
  324.     MAILSTREAM *stream;
  325.     char *mailbox;
  326. {
  327.   return map_manage (stream,mailbox,"Create",NIL);
  328. }
  329.  
  330.  
  331. /* Mail Access Protocol delete mailbox
  332.  * Accepts: mail stream
  333.  *        mailbox name to delete
  334.  * Returns: T on success, NIL on failure
  335.  */
  336.  
  337. long map_delete (stream,mailbox)
  338.     MAILSTREAM *stream;
  339.     char *mailbox;
  340. {
  341.   return map_manage (stream,mailbox,"Delete",NIL);
  342. }
  343.  
  344.  
  345. /* Mail Access Protocol rename mailbox
  346.  * Accepts: mail stream
  347.  *        old mailbox name
  348.  *        new mailbox name
  349.  * Returns: T on success, NIL on failure
  350.  */
  351.  
  352. long map_rename (stream,old,new)
  353.     MAILSTREAM *stream;
  354.     char *old;
  355.     char *new;
  356. {
  357.   return map_manage (stream,old,"Rename",new);
  358. }
  359.  
  360. /* Mail Access Protocol manage a mailbox
  361.  * Accepts: mail stream
  362.  *        mailbox to manipulate
  363.  *        command to execute
  364.  *        optional second argument
  365.  * Returns: T on success, NIL on failure
  366.  */
  367.  
  368. long map_manage (stream,mailbox,command,arg2)
  369.     MAILSTREAM *stream;
  370.     char *mailbox;
  371.     char *command;
  372.     char *arg2;
  373. {
  374.   MAILSTREAM *st = stream;
  375.   long ret;
  376.   char *s,tmp[MAILTMPLEN];
  377.   IMAPPARSEDREPLY *reply;
  378.   if (!(stream && LOCAL)) {    /* if a prototype stream requested */
  379.     if (!(stream = mail_open (NIL,mailbox,OP_HALFOPEN))) {
  380.       mm_log ("Can't access server",ERROR);
  381.       return NIL;
  382.     }
  383.   }
  384.                 /* KLUDGE: nuke host name in second argument */
  385.   if (arg2 && (*arg2 == '{') && (s = strchr (arg2,'}'))) arg2 = s + 1;
  386.                 /* get mailbox name */
  387.   mail_valid_net (mailbox,&imapdriver,NIL,tmp);
  388.                 /* send management command */
  389.   ret = imap_OK (stream,reply = imap_send (stream,command,tmp,arg2));
  390.   mm_log (reply->text, ret ? (long) NIL : ERROR);
  391.                 /* toss out temporary stream */
  392.   if (st != stream) mail_close (stream);
  393.   return ret;
  394. }
  395.  
  396. /* Mail Access Protocol open
  397.  * Accepts: stream to open
  398.  * Returns: stream to use on success, NIL on failure
  399.  */
  400.  
  401. MAILSTREAM *map_open (stream)
  402.     MAILSTREAM *stream;
  403. {
  404.   long i,j;
  405.   char username[MAILTMPLEN],pwd[MAILTMPLEN],tmp[MAILTMPLEN];
  406.   NETMBX mb;
  407.   char *s;
  408.   IMAPPARSEDREPLY *reply = NIL;
  409.                 /* return prototype for OP_PROTOTYPE call */
  410.   if (!stream) return &imapproto;
  411.   mail_valid_net_parse (stream->mailbox,&mb);
  412.                 /* default mailbox name */
  413.   if (!*mb.mailbox) strcpy (mb.mailbox,mb.bbdflag ? "general" : "INBOX");
  414.   if (LOCAL) {            /* if stream opened earlier by us */
  415.     if (strcmp (ucase (strcpy (tmp,mb.host)),
  416.         ucase (strcpy (pwd,imap_host (stream))))) {
  417.                 /* if hosts are different punt it */
  418.       sprintf (tmp,"Closing connection to %s",imap_host (stream));
  419.       if (!stream->silent) mm_log (tmp,(long) NIL);
  420.       map_close (stream);
  421.     }
  422.     else {            /* else recycle if still alive */
  423.       i = stream->silent;    /* temporarily mark silent */
  424.       stream->silent = T;    /* don't give mm_exists() events */
  425.       j = map_ping (stream);    /* learn if stream still alive */
  426.       stream->silent = i;    /* restore prior state */
  427.       if (j) {            /* was stream still alive? */
  428.     sprintf (tmp,"Reusing connection to %s",mb.host);
  429.     if (!stream->silent) mm_log (tmp,(long) NIL);
  430.     map_do_gc (stream,GC_TEXTS);
  431.       }
  432.       else map_close (stream);
  433.     }
  434.     mail_free_cache (stream);
  435.   }
  436.  
  437.   if (!LOCAL) {            /* open new connection if no recycle */
  438.     stream->local = fs_get (sizeof (IMAPLOCAL));
  439.     LOCAL->reply.line = LOCAL->reply.tag = LOCAL->reply.key =
  440.       LOCAL->reply.text = LOCAL->prefix = NIL;
  441.     LOCAL->use_body = LOCAL->use_find = LOCAL->use_bboard =
  442.       LOCAL->use_purge = T;    /* assume maximal server */
  443.                 /* try authenticated open */
  444.     if (LOCAL->tcpstream = (stream->anonymous || mb.anoflag || mb.port) ? NIL :
  445.     tcp_aopen (mb.host,"/etc/rimapd")) {
  446.                 /* if success, see if reasonable banner */
  447.       if ((s = tcp_getline (LOCAL->tcpstream)) && (*s == '*') &&
  448.       (reply = imap_parse_reply (stream,s)) && !strcmp (reply->tag,"*"))
  449.     imap_parse_unsolicited (stream,reply);
  450.       else {            /* nuke the stream then */
  451.     if (s) fs_give ((void **) &s);
  452.     if (LOCAL->tcpstream) {
  453.       tcp_close (LOCAL->tcpstream);
  454.       LOCAL->tcpstream = NIL;
  455.     }
  456.       }
  457.     }
  458.     if (!LOCAL->tcpstream &&    /* try to open ordinary connection */
  459.     (LOCAL->tcpstream = tcp_open(mb.host,mb.port?(long)mb.port:map_port))&&
  460.     (!imap_OK (stream,reply = imap_reply (stream,NIL)))) {
  461.       mm_log (reply->text,ERROR);
  462.       map_close (stream);    /* failed, clean up */
  463.     }
  464.  
  465.     if (LOCAL && LOCAL->tcpstream && !strcmp (reply->key,"OK")) {
  466.                 /* only so many tries to login */
  467.       if (!lhostn) lhostn = cpystr (tcp_localhost (LOCAL->tcpstream));
  468.       for (i = 0; i < map_maxlogintrials; ++i) {
  469.     *pwd = 0;        /* get password */
  470.                 /* if caller wanted anonymous access */
  471.     if ((mb.anoflag || stream->anonymous) && !i) {
  472.       strcpy (username,"anonymous");
  473.       strcpy (pwd,*lhostn ? lhostn : "foo");
  474.     }
  475.     else mm_login (tcp_host (LOCAL->tcpstream),username,pwd,i);
  476.                 /* abort if he refuses to give a password */
  477.     if (*pwd == '\0') i = map_maxlogintrials;
  478.     else {            /* send "LOGIN username pwd" */
  479.       if (imap_OK (stream,reply = imap_send (stream,"LOGIN",username,
  480.                          pwd))) break;
  481.                 /* output failure and try again */
  482.       mm_log (reply->text,WARN);
  483.                 /* give up now if connection died */
  484.       if (!strcmp (reply->key,"BYE")) i = map_maxlogintrials;
  485.     }
  486.       }
  487.                 /* give up if too many failures */
  488.       if (i >=  map_maxlogintrials) {
  489.     mm_log (*pwd ? "Too many login failures":"Login aborted",ERROR);
  490.     map_close (stream);
  491.       }
  492.       else stream->anonymous = strcmp (username,"anonymous") ? NIL : T;
  493.     }
  494.                 /* failed utterly to open */
  495.     if (LOCAL && !LOCAL->tcpstream) map_close (stream);
  496.   }
  497.  
  498.   if (LOCAL) {            /* have a connection now??? */
  499.     stream->sequence++;        /* bump sequence number */
  500.                 /* prepare to update mailbox name */
  501.     fs_give ((void **) &stream->mailbox);
  502.     if (stream->halfopen ||    /* send "SELECT/EXAMINE/BBOARD mailbox" */
  503.     !imap_OK (stream,reply = imap_send (stream,mb.bbdflag ? "BBOARD" :
  504.                         (stream->readonly ? "EXAMINE" :
  505.                          "SELECT"),mb.mailbox,NIL))) {
  506.       sprintf (tmp,"{%s}<no_mailbox>",imap_host (stream));
  507.       stream->mailbox = cpystr (tmp);
  508.       if (!stream->halfopen) {    /* output error message if didn't ask for it */
  509.     mm_log (reply->text,ERROR);
  510.     stream->halfopen = T;
  511.       }
  512.                 /* make sure dummy message counts */
  513.       mail_exists (stream,(long) 0);
  514.       mail_recent (stream,(long) 0);
  515.     }
  516.     else {            /* update mailbox name */
  517.       sprintf (tmp,"%s{%s}%s",mb.bbdflag ? "*" : "",
  518.            imap_host (stream),mb.mailbox);
  519.       stream->mailbox = cpystr (tmp);
  520.       reply->text[11] = '\0';    /* note if server said it was readonly */
  521.       stream->readonly = !strcmp (ucase (reply->text),"[READ-ONLY]");
  522.     }
  523.     if (!(stream->nmsgs || stream->silent))
  524.       mm_log ("Mailbox is empty",(long) NIL);
  525.     if (stream->scache && LOCAL->use_purge &&
  526.     !strcmp (imap_send (stream,"PURGE ALWAYS",NIL,NIL)->key,"BAD"))
  527.       LOCAL->use_purge = NIL;
  528.   }
  529.                 /* give up if nuked during startup */
  530.   if (LOCAL && !LOCAL->tcpstream) map_close (stream);
  531.   return LOCAL ? stream : NIL;    /* if stream is alive, return to caller */
  532. }
  533.  
  534. /* Mail Access Protocol close
  535.  * Accepts: MAIL stream
  536.  */
  537.  
  538. void map_close (stream)
  539.     MAILSTREAM *stream;
  540. {
  541.   IMAPPARSEDREPLY *reply;
  542.   if (stream && LOCAL) {    /* send "LOGOUT" */
  543.     if (LOCAL->tcpstream &&
  544.     !imap_OK (stream,reply = imap_send (stream,"LOGOUT",NIL,NIL)))
  545.       mm_log (reply->text,WARN);
  546.                 /* close TCP connection if still open */
  547.     if (LOCAL->tcpstream) tcp_close (LOCAL->tcpstream);
  548.     LOCAL->tcpstream = NIL;
  549.                 /* free up memory */
  550.     if (LOCAL->reply.line) fs_give ((void **) &LOCAL->reply.line);
  551.     map_do_gc (stream,GC_TEXTS);/* nuke the cached strings */
  552.                 /* nuke the local data */
  553.     fs_give ((void **) &stream->local);
  554.   }
  555. }
  556.  
  557.  
  558. /* Mail Access Protocol fetch fast information
  559.  * Accepts: MAIL stream
  560.  *        sequence
  561.  *
  562.  * Generally, map_fetchstructure is preferred
  563.  */
  564.  
  565. void map_fetchfast (stream,sequence)
  566.     MAILSTREAM *stream;
  567.     char *sequence;
  568. {                /* send "FETCH sequence FAST" */
  569.   IMAPPARSEDREPLY *reply;
  570.   if (!imap_OK (stream,reply = imap_send (stream,"FETCH",sequence,"FAST")))
  571.     mm_log (reply->text,ERROR);
  572. }
  573.  
  574.  
  575. /* Mail Access Protocol fetch flags
  576.  * Accepts: MAIL stream
  577.  *        sequence
  578.  */
  579.  
  580. void map_fetchflags (stream,sequence)
  581.     MAILSTREAM *stream;
  582.     char *sequence;
  583. {                /* send "FETCH sequence FLAGS" */
  584.   IMAPPARSEDREPLY *reply;
  585.   if (!imap_OK (stream,reply = imap_send (stream,"FETCH",sequence,"FLAGS")))
  586.     mm_log (reply->text,ERROR);
  587. }
  588.  
  589. /* Mail Access Protocol fetch structure
  590.  * Accepts: MAIL stream
  591.  *        message # to fetch
  592.  *        pointer to return body
  593.  * Returns: envelope of this message, body returned in body value
  594.  *
  595.  * Fetches the "fast" information as well
  596.  */
  597.  
  598. ENVELOPE *map_fetchstructure (stream,msgno,body)
  599.     MAILSTREAM *stream;
  600.     long msgno;
  601.     BODY **body;
  602. {
  603.   long i = msgno;
  604.   long j = min (msgno + map_lookahead - 1,stream->nmsgs);
  605.   char seq[20];
  606.   LONGCACHE *lelt;
  607.   ENVELOPE **env;
  608.   BODY **b;
  609.   IMAPPARSEDREPLY *reply;
  610.   if (stream->scache) {        /* short cache */
  611.     if (msgno != stream->msgno){/* flush old poop if a different message */
  612.       mail_free_envelope (&stream->env);
  613.       mail_free_body (&stream->body);
  614.     }
  615.     stream->msgno = msgno;
  616.     env = &stream->env;        /* get pointers to envelope and body */
  617.     b = &stream->body;
  618.     sprintf (seq,"%ld",msgno);    /* never lookahead with a short cache */
  619.   }
  620.   else {            /* long cache */
  621.     lelt = mail_lelt (stream,msgno);
  622.     env = &lelt->env;        /* get pointers to envelope and body */
  623.     b = &lelt->body;
  624.     if (msgno != stream->nmsgs)    /* determine lookahead range */
  625.       while (i < j && !mail_lelt (stream,i+1)->env) i++;
  626.     sprintf (seq,"%ld:%ld",msgno,i);
  627.   }
  628.                 /* have the poop we need? */
  629.   if ((body && !*b && LOCAL->use_body) || !*env) {
  630.     mail_free_envelope (env);    /* flush old envelope and body */
  631.     mail_free_body (b);
  632.     if (!(body && LOCAL->use_body &&
  633.       (LOCAL->use_body =
  634.        (strcmp ((reply = imap_send(stream,"FETCH",seq,"FULL"))->key,"BAD")?
  635.         T : NIL)))) reply = imap_send (stream,"FETCH",seq,"ALL");
  636.     if (!imap_OK (stream,reply)) {
  637.       mm_log (reply->text,ERROR);
  638.       return NIL;
  639.     }
  640.   }
  641.   if (body) *body = *b;        /* return the body */
  642.   return *env;            /* return the envelope */
  643. }
  644.  
  645. /* Mail Access Protocol fetch message header
  646.  * Accepts: MAIL stream
  647.  *        message # to fetch
  648.  * Returns: message header in RFC822 format
  649.  */
  650.  
  651. char *map_fetchheader (stream,msgno)
  652.     MAILSTREAM *stream;
  653.     long msgno;
  654. {
  655.   char tmp[40];
  656.   long i = msgno - 1;
  657.   IMAPPARSEDREPLY *reply;
  658.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  659.   if (!elt->data1) {        /* not if already cached */
  660.     sprintf (tmp,"FETCH %ld",msgno);
  661.     if (!imap_OK (stream,    /* send "FETCH msgno RFC822.HEADER" */
  662.           reply = imap_send (stream,tmp,elt->data2 ?
  663.                      "RFC822.HEADER" :
  664.                      "(RFC822.HEADER RFC822.TEXT)",NIL)))
  665.       mm_log (reply->text,ERROR);
  666.   }
  667.   return elt->data1 ? (char *) elt->data1 : "";
  668. }
  669.  
  670.  
  671. /* Mail Access Protocol fetch message text (only)
  672.     body only;
  673.  * Accepts: MAIL stream
  674.  *        message # to fetch
  675.  * Returns: message text in RFC822 format
  676.  */
  677.  
  678. char *map_fetchtext (stream,msgno)
  679.     MAILSTREAM *stream;
  680.     long msgno;
  681. {
  682.   char seq[20];
  683.   long i = msgno - 1;
  684.   IMAPPARSEDREPLY *reply;
  685.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  686.   if (!elt->data2) {        /* send "FETCH msgno RFC822.TEXT" */
  687.     sprintf (seq,"%ld",msgno);
  688.     if (!imap_OK (stream,reply = imap_send(stream,"FETCH",seq,"RFC822.TEXT")))
  689.       mm_log (reply->text,ERROR);
  690.   }
  691.   return elt->data2 ? (char *) elt->data2 : "";
  692. }
  693.  
  694. /* Mail Access Protocol fetch message body as a structure
  695.  * Accepts: Mail stream
  696.  *        message # to fetch
  697.  *        section specifier
  698.  *        pointer to length
  699.  * Returns: pointer to section of message body
  700.  */
  701.  
  702. char *map_fetchbody (stream,m,sec,len)
  703.     MAILSTREAM *stream;
  704.     long m;
  705.     char *sec;
  706.     unsigned long *len;
  707. {
  708.   BODY *b;
  709.   PART *pt;
  710.   char *s = sec;
  711.   char **ss;
  712.   unsigned long i;
  713.   char seq[40];
  714.   IMAPPARSEDREPLY *reply;
  715.   *len = 0;            /* in case failure */
  716.                 /* make sure have a body */
  717.   if (!(LOCAL->use_body && map_fetchstructure (stream,m,&b) && b)) {
  718.                 /* bodies not supported, wanted section 1? */
  719.     if (strcmp (sec,"1")) return NIL;
  720.                 /* yes, return text */
  721.     *len = strlen (s = map_fetchtext (stream,m));
  722.     return s;
  723.   }
  724.   if (!(s && *s && ((i = strtol (s,&s,10)) > 0))) return NIL;
  725.   do {                /* until find desired body part */
  726.                 /* multipart content? */
  727.     if (b->type == TYPEMULTIPART) {
  728.       pt = b->contents.part;    /* yes, find desired part */
  729.       while (--i && (pt = pt->next));
  730.       if (!pt) return NIL;    /* bad specifier */
  731.                 /* note new body, check valid nesting */
  732.       if (((b = &pt->body)->type == TYPEMULTIPART) && !*s) return NIL;
  733.     }
  734.     else if (i != 1) return NIL;/* otherwise must be section 1 */
  735.                 /* need to go down further? */
  736.     if (i = *s) switch (b->type) {
  737.     case TYPEMESSAGE:        /* embedded message, calculate new base */
  738.       b = b->contents.msg.body;    /* get its body, drop into multipart case */
  739.     case TYPEMULTIPART:        /* multipart, get next section */
  740.       if ((*s++ == '.') && (i = strtol (s,&s,10)) > 0) break;
  741.     default:            /* bogus subpart specification */
  742.       return NIL;
  743.     }
  744.   } while (i);
  745.  
  746.                 /* lose if body bogus */
  747.   if ((!b) || b->type == TYPEMULTIPART) return NIL;
  748.   switch (b->type) {        /* decide where the data is based on type */
  749.   case TYPEMESSAGE:        /* encapsulated message */
  750.     ss = &b->contents.msg.text;
  751.     break;
  752.   case TYPETEXT:        /* textual data */
  753.     ss = (char **) &b->contents.text;
  754.     break;
  755.   default:            /* otherwise assume it is binary */
  756.     ss = (char **) &b->contents.binary;
  757.     break;
  758.   }
  759.   if (!*ss) {            /* fetch data if don't have it yet */
  760.     sprintf (seq,"%ld BODY[%s]",m,sec);
  761.     if (!imap_OK (stream,reply = imap_send (stream,"FETCH",seq,NIL)))
  762.       mm_log (reply->text,ERROR);
  763.   }
  764.                 /* return data size if have data */
  765.   if (s = *ss) *len = b->size.bytes;
  766.   return s;
  767. }
  768.  
  769. /* Mail Access Protocol set flag
  770.  * Accepts: MAIL stream
  771.  *        sequence
  772.  *        flag(s)
  773.  */
  774.  
  775. void map_setflag (stream,sequence,flag)
  776.     MAILSTREAM *stream;
  777.     char *sequence;
  778.     char *flag;
  779. {
  780.   char *tmp = (char *) fs_get (20 + strlen (sequence));
  781.   IMAPPARSEDREPLY *reply;
  782.                 /* "STORE sequence +Flags flag" */
  783.   sprintf (tmp,"STORE %s +Flags",sequence);
  784.   if (!imap_OK (stream,reply = imap_send (stream,tmp,flag,NIL)))
  785.     mm_log (reply->text,ERROR);
  786.   fs_give ((void **) &tmp);
  787. }
  788.  
  789.  
  790. /* Mail Access Protocol clear flag
  791.  * Accepts: MAIL stream
  792.  *        sequence
  793.  *        flag(s)
  794.  */
  795.  
  796. void map_clearflag (stream,sequence,flag)
  797.     MAILSTREAM *stream;
  798.     char *sequence;
  799.     char *flag;
  800. {
  801.   char *tmp = (char *) fs_get (20 + strlen (sequence));
  802.   IMAPPARSEDREPLY *reply;
  803.                 /* "STORE sequence -Flags flag" */
  804.   sprintf (tmp,"STORE %s -Flags",sequence);
  805.   if (!imap_OK (stream,reply = imap_send (stream,tmp,flag,NIL)))
  806.     mm_log (reply->text,ERROR);
  807.   fs_give ((void **) &tmp);
  808. }
  809.  
  810. /* Mail Access Protocol search for messages
  811.  * Accepts: MAIL stream
  812.  *        search criteria
  813.  */
  814.  
  815. void map_search (stream,criteria)
  816.     MAILSTREAM *stream;
  817.     char *criteria;
  818. {
  819.   long i,j;
  820.   char *s;
  821.   IMAPPARSEDREPLY *reply;
  822.   MESSAGECACHE *elt;
  823.                 /* do the SEARCH */
  824.   if (imap_OK (stream,reply = imap_send (stream,"SEARCH",criteria,NIL))) {
  825.     if (stream->scache) return;    /* can never pre-fetch with a short cache */
  826.     s = LOCAL->tmp;        /* build sequence in temporary buffer */
  827.     *s = '\0';            /* initially nothing */
  828.                 /* search through mailbox */
  829.     for (i = 1; i <= stream->nmsgs; ++i)
  830.                 /* for searched messages with no envelope */
  831.       if ((elt = mail_elt (stream,i)) && elt->searched &&
  832.       !mail_lelt (stream,i)->env) {
  833.                 /* prepend with comma if not first time */
  834.     if (LOCAL->tmp[0]) *s++ = ',';
  835.     sprintf (s,"%ld",j = i);/* output message number */
  836.     s += strlen (s);    /* point at end of string */
  837.                 /* search for possible end of range */
  838.     while (i < stream->nmsgs && (elt = mail_elt (stream,i+1)) &&
  839.            elt->searched && !mail_lelt (stream,i+1)->env) i++;
  840.     if (i != j) {        /* if a range */
  841.       sprintf (s,":%ld",i);    /* output delimiter and end of range */
  842.       s += strlen (s);    /* point at end of string */
  843.     }
  844.       }
  845.     if (LOCAL->tmp[0]) {    /* anything to pre-fetch? */
  846.       s = cpystr (LOCAL->tmp);    /* yes, copy sequence */
  847.       if (!imap_OK (stream,reply = imap_send (stream,"FETCH",s,"ALL")))
  848.     mm_log (reply->text,ERROR);
  849.       fs_give ((void **) &s);    /* flush copy of sequence */
  850.     }
  851.   }
  852.   else mm_log (reply->text,ERROR);
  853. }
  854.  
  855. /* Mail Access Protocol ping mailbox
  856.  * Accepts: MAIL stream
  857.  * Returns: T if stream still alive, else NIL
  858.  */
  859.  
  860. long map_ping (stream)
  861.     MAILSTREAM *stream;
  862. {
  863.   return (LOCAL->tcpstream &&    /* send "NOOP" */
  864.       imap_OK (stream,imap_send (stream,"NOOP",NIL,NIL))) ? T : NIL;
  865. }
  866.  
  867.  
  868. /* Mail Access Protocol check mailbox
  869.  * Accepts: MAIL stream
  870.  */
  871.  
  872. void map_check (stream)
  873.     MAILSTREAM *stream;
  874. {
  875.                 /* send "CHECK" */
  876.   IMAPPARSEDREPLY *reply = imap_send (stream,"CHECK",NIL,NIL);
  877.   mm_log (reply->text,imap_OK (stream,reply) ? (long) NIL : ERROR);
  878. }
  879.  
  880.  
  881. /* Mail Access Protocol expunge mailbox
  882.  * Accepts: MAIL stream
  883.  */
  884.  
  885. void map_expunge (stream)
  886.     MAILSTREAM *stream;
  887. {
  888.                 /* send "EXPUNGE" */
  889.   IMAPPARSEDREPLY *reply = imap_send (stream,"EXPUNGE",NIL,NIL);
  890.   mm_log (reply->text,imap_OK (stream,reply) ? (long) NIL : ERROR);
  891. }
  892.  
  893. /* Mail Access Protocol copy message(s)
  894.     s;
  895.  * Accepts: MAIL stream
  896.  *        sequence
  897.  *        destination mailbox
  898.  * Returns: T if successful else NIL
  899.  */
  900.  
  901. long map_copy (stream,sequence,mailbox)
  902.     MAILSTREAM *stream;
  903.     char *sequence;
  904.     char *mailbox;
  905. {
  906.   IMAPPARSEDREPLY *reply;
  907.   if (!LOCAL->tcpstream) {    /* not valid on dead stream */
  908.     mm_log ("Copy rejected: connection to remote IMAP server closed",ERROR);
  909.     return NIL;
  910.   }
  911.                 /* send "COPY sequence mailbox" */
  912.   if (!imap_OK (stream,reply = imap_send (stream,"COPY",sequence,mailbox))) {
  913.     mm_log (reply->text,ERROR);
  914.     return NIL;
  915.   }
  916.   map_setflag (stream,sequence,"\\Seen");
  917.   return T;
  918. }
  919.  
  920.  
  921. /* Mail Access Protocol move message(s)
  922.     s;
  923.  * Accepts: MAIL stream
  924.  *        sequence
  925.  *        destination mailbox
  926.  * Returns: T if successful else NIL
  927.  */
  928.  
  929. long map_move (stream,sequence,mailbox)
  930.     MAILSTREAM *stream;
  931.     char *sequence;
  932.     char *mailbox;
  933. {
  934.   IMAPPARSEDREPLY *reply;
  935.   if (!LOCAL->tcpstream) {    /* not valid on dead stream */
  936.     mm_log ("Move rejected: connection to remote IMAP server closed",ERROR);
  937.     return NIL;
  938.   }
  939.                 /* send "COPY sequence mailbox" */
  940.   if (!imap_OK (stream,reply = imap_send (stream,"COPY",sequence,mailbox))) {
  941.     mm_log (reply->text,ERROR);
  942.     return NIL;
  943.   }
  944.   map_setflag (stream,sequence,"\\Deleted \\Seen");
  945.   return T;
  946. }
  947.  
  948. /* Mail Access Protocol append message string
  949.  * Accepts: mail stream
  950.  *        destination mailbox
  951.  *        stringstruct of message to append
  952.  * Returns: T on success, NIL on failure
  953.  */
  954.  
  955. long map_append (stream,mailbox,message)
  956.     MAILSTREAM *stream;
  957.     char *mailbox;
  958.     STRING *message;
  959. {
  960.   MAILSTREAM *st = stream;
  961.   long ret;
  962.   char tmp[MAILTMPLEN];
  963.   IMAPPARSEDREPLY *reply;
  964.                 /* in case useful stream not given */
  965.   if (!(stream && LOCAL && LOCAL->tcpstream)) {
  966.     if (!(stream = mail_open (NIL,mailbox,OP_HALFOPEN))) {
  967.       mm_log ("Can't access server for append",ERROR);
  968.       return NIL;
  969.     }
  970.   }
  971.                 /* get mailbox name */
  972.   if ((ret = mail_valid_net (mailbox,&imapdriver,NIL,tmp) ? T : NIL) &&
  973.       (!imap_OK (stream,    /* report error if it choked */
  974.          reply = imap_send_literal (stream,"APPEND",tmp,message)))) {
  975.     mm_log (reply->text,ERROR);
  976.     ret = NIL;
  977.   }
  978.                 /* toss out temporary stream */
  979.   if (st != stream) mail_close (stream);
  980.   return ret;            /* return */
  981. }
  982.  
  983. /* Mail Access Protocol garbage collect stream
  984.  * Accepts: Mail stream
  985.  *        garbage collection flags
  986.  */
  987.  
  988. void map_gc (stream,gcflags)
  989.     MAILSTREAM *stream;
  990.     long gcflags;
  991. {
  992.   char tmp[MAILTMPLEN];
  993.   if (stream->nmsgs) {        /* nothing to purge if no messages */
  994.     sprintf (tmp,"1:%ld",stream->nmsgs);
  995.     if (LOCAL->use_purge && (gcflags & GC_ELT) &&
  996.     !strcmp (imap_send (stream,"PURGE STATUS",tmp,NIL)->key,"BAD"))
  997.       LOCAL->use_purge = NIL;
  998.     if (LOCAL->use_purge && (gcflags & GC_ENV) &&
  999.     !strcmp (imap_send (stream,"PURGE STRUCTURE",tmp,NIL)->key,"BAD"))
  1000.       LOCAL->use_purge = NIL;
  1001.     if (LOCAL->use_purge && (gcflags & GC_TEXTS) &&
  1002.     !strcmp (imap_send (stream,"PURGE TEXTS",tmp,NIL)->key,"BAD"))
  1003.       LOCAL->use_purge = NIL;
  1004.   }
  1005.   map_do_gc (stream,gcflags);    /* now call our worker routine */
  1006. }
  1007.  
  1008.  
  1009. /* Mail Access Protocol garbage collect stream worker routine
  1010.  * Accepts: Mail stream
  1011.  *        garbage collection flags
  1012.  */
  1013.  
  1014. void map_do_gc (stream,gcflags)
  1015.     MAILSTREAM *stream;
  1016.     long gcflags;
  1017. {
  1018.   unsigned long i;
  1019.   MESSAGECACHE *elt;
  1020.   LONGCACHE *lelt;
  1021.                 /* make sure the cache is large enough */
  1022.   (*mailcache) (stream,stream->nmsgs,CH_SIZE);
  1023.   if (gcflags & GC_TEXTS) {    /* garbage collect texts? */
  1024.     for (i = 1; i <= stream->nmsgs; ++i)
  1025.       if (elt = (MESSAGECACHE *) (*mailcache) (stream,i,CH_ELT)) {
  1026.     if (elt->data1) fs_give ((void **) &elt->data1);
  1027.     if (elt->data2) fs_give ((void **) &elt->data2);
  1028.     if (!stream->scache) map_gc_body ((lelt = mail_lelt (stream,i))->body);
  1029.       }
  1030.     map_gc_body (stream->body);    /* free texts from short cache body */
  1031.   }
  1032.                 /* gc cache if requested and unlocked */
  1033.   if (gcflags & GC_ELT) for (i = 1; i <= stream->nmsgs; ++i)
  1034.     if ((elt = (MESSAGECACHE *) (*mailcache) (stream,i,CH_ELT)) &&
  1035.     (elt->lockcount == 1)) (*mailcache) (stream,i,CH_FREE);
  1036. }
  1037.  
  1038. /* Mail Access Protocol garbage collect body texts
  1039.  * Accepts: body to GC
  1040.  */
  1041.  
  1042. void map_gc_body (body)
  1043.     BODY *body;
  1044. {
  1045.   PART *part;
  1046.   if (body) switch (body->type) {
  1047.   case TYPETEXT:        /* unformatted text */
  1048.     if (body->contents.text) fs_give ((void **) &body->contents.text);
  1049.     break;
  1050.   case TYPEMULTIPART:        /* multiple part */
  1051.     if (part = body->contents.part) do map_gc_body (&part->body);
  1052.     while (part = part->next);
  1053.     break;
  1054.   case TYPEMESSAGE:        /* encapsulated message */
  1055.     map_gc_body (body->contents.msg.body);
  1056.     if (body->contents.msg.text)
  1057.       fs_give ((void **) &body->contents.msg.text);
  1058.     break;
  1059.   case TYPEAPPLICATION:        /* application data */
  1060.   case TYPEAUDIO:        /* audio */
  1061.   case TYPEIMAGE:        /* static image */
  1062.   case TYPEVIDEO:        /* video */
  1063.     if (body->contents.binary) fs_give (&body->contents.binary);
  1064.     break;
  1065.   default:
  1066.     break;
  1067.   }
  1068. }
  1069.  
  1070. /* Internal routines */
  1071.  
  1072.  
  1073. /* Mail Access Protocol return host name
  1074.  * Accepts: MAIL stream
  1075.  * Returns: host name
  1076.  */
  1077.  
  1078. char *imap_host (stream)
  1079.     MAILSTREAM *stream;
  1080. {
  1081.                 /* return host name on stream if open */
  1082.   return (LOCAL && LOCAL->tcpstream) ? tcp_host (LOCAL->tcpstream) :
  1083.     "<closed stream>";
  1084. }
  1085.  
  1086. /* Mail Access Protocol send command
  1087.  * Accepts: MAIL stream
  1088.  *        command
  1089.  *        command argument
  1090.  *        second command argument
  1091.  * Returns: parsed reply
  1092.  */
  1093.  
  1094. IMAPPARSEDREPLY *imap_send (stream,cmd,arg,arg2)
  1095.     MAILSTREAM *stream;
  1096.     char *cmd;
  1097.     char *arg;
  1098.     char *arg2;
  1099. {
  1100.   IMAPPARSEDREPLY *reply = NIL;
  1101.   if (arg2 && strpbrk (arg2,"\012\015\"%{\\")) {
  1102.     STRING s;
  1103.     INIT (&s,mail_string,(void *) arg2,(unsigned long) strlen (arg2));
  1104.     reply = imap_send_literal (stream,cmd,arg,&s);
  1105.   }
  1106.   else {
  1107.     char tag[7];
  1108.                   /* gensym a new tag */
  1109.     sprintf (tag,"A%05ld",stream->gensym++);
  1110.     if (!LOCAL->tcpstream) return imap_fake(stream,tag,"OK No-op dead stream");
  1111.                 /* begin command */
  1112.     sprintf (LOCAL->tmp,"%s %s",tag,cmd);
  1113.     mail_lock (stream);        /* lock up the stream */
  1114.     if (arg) {            /* argument present? */
  1115.       sprintf (LOCAL->tmp + strlen (LOCAL->tmp)," %s",arg);
  1116.                 /* second argument present? */
  1117.       if (arg2) sprintf (LOCAL->tmp + strlen (LOCAL->tmp),
  1118.              strchr (arg2,' ') ? " \"%s\"" : " %s",arg2);
  1119.     }
  1120.                 /* output to debugging telemetry */
  1121.     if (stream->debug) mm_dlog (LOCAL->tmp);
  1122.     strcat (LOCAL->tmp,"\015\012");
  1123.                 /* send the command */
  1124.     if (tcp_soutr (LOCAL->tcpstream,LOCAL->tmp))
  1125.       reply = imap_reply (stream,tag);
  1126.     mail_unlock (stream);    /* unlock stream */
  1127.     if (!reply) {        /* close TCP connection if it died */
  1128.       tcp_close (LOCAL->tcpstream);
  1129.       LOCAL->tcpstream = NIL;
  1130.       return imap_fake (stream,tag,"BYE IMAP connection broken in send");
  1131.     }
  1132.   }
  1133.   return reply;            /* return reply to caller */
  1134. }
  1135.  
  1136. /* Mail Access Protocol send command with literal argument
  1137.  * Accepts: MAIL stream
  1138.  *        command
  1139.  *        command argument
  1140.  *        second command argument
  1141.  * Returns: parsed reply
  1142.  */
  1143.  
  1144. IMAPPARSEDREPLY *imap_send_literal (stream,cmd,arg,arg2)
  1145.     MAILSTREAM *stream;
  1146.     char *cmd;
  1147.     char *arg;
  1148.     STRING *arg2;
  1149. {
  1150.   char tag[7];
  1151.   char *s = NIL;
  1152.   unsigned long i = SIZE (arg2);
  1153.   IMAPPARSEDREPLY *reply = NIL;
  1154.   if (!LOCAL->tcpstream) return imap_fake (stream,tag,"OK No-op dead stream");
  1155.                   /* gensym a new tag */
  1156.   sprintf (tag,"A%05ld",stream->gensym++);
  1157.                 /* begin command */
  1158.   sprintf (LOCAL->tmp,"%s %s %s {%ld}",tag,cmd,arg,i);
  1159.   mail_lock (stream);        /* lock up the stream */
  1160.                 /* output debugging telemetry */
  1161.   if (stream->debug) mm_dlog (LOCAL->tmp);
  1162.   strcat (LOCAL->tmp,"\015\012");
  1163.                 /* send the command */
  1164.   if (tcp_soutr (LOCAL->tcpstream,LOCAL->tmp) &&
  1165.       !strcmp ((reply = imap_reply (stream,tag))->tag,"+")) {
  1166.                 /* dump the message */
  1167.     while (i && tcp_sout (LOCAL->tcpstream,arg2->curpos,arg2->cursize)) {
  1168.       i -= arg2->cursize;    /* note that we wrote out this much */
  1169.       arg2->curpos += (arg2->cursize - 1);
  1170.       arg2->cursize = 1;
  1171.       SNX(arg2);        /* advance to next buffer's worth */
  1172.     }
  1173.     if ((!i) && tcp_soutr (LOCAL->tcpstream,"\015\012"))
  1174.       reply = imap_reply (stream,tag);
  1175.     else reply = NIL;
  1176.   }
  1177.   mail_unlock (stream);        /* unlock stream */
  1178.   if (!reply) {            /* close TCP connection if it died */
  1179.     tcp_close (LOCAL->tcpstream);
  1180.     LOCAL->tcpstream = NIL;
  1181.     return imap_fake (stream,tag,"BYE IMAP connection broken in send");
  1182.   }
  1183.   return reply;            /* return reply to caller */
  1184. }
  1185.  
  1186. /* Mail Access Protocol get reply
  1187.  * Accepts: MAIL stream
  1188.  *        tag to search or NIL if want a greeting
  1189.  * Returns: parsed reply, never NIL
  1190.  */
  1191.  
  1192. IMAPPARSEDREPLY *imap_reply (stream,tag)
  1193.     MAILSTREAM *stream;
  1194.     char *tag;
  1195. {
  1196.   IMAPPARSEDREPLY *reply;
  1197.   while (LOCAL->tcpstream) {    /* parse reply from server */
  1198.     if (reply = imap_parse_reply (stream,tcp_getline (LOCAL->tcpstream))) {
  1199.                 /* untagged response means unsolicited data */
  1200.       if (!strcmp (reply->tag,"*")) {
  1201.     imap_parse_unsolicited (stream,reply);
  1202.     if (tag) continue;    /* waiting for a response */
  1203.     return reply;        /* return greeting */
  1204.       }
  1205.       else {            /* not unsolicited reponse */
  1206.     if (tag && ((!strcmp (tag,reply->tag)) || (!strcmp (reply->tag,"+"))))
  1207.       return reply;        /* return if desired tag or + */
  1208.                 /* report bogon */
  1209.     sprintf (LOCAL->tmp,"Unexpected tagged response: %.80s %.80s %.80s",
  1210.          reply->tag,reply->key,reply->text);
  1211.     mm_log (LOCAL->tmp,WARN);
  1212.       }
  1213.     }
  1214.   }
  1215.   return imap_fake (stream,tag,"BYE IMAP connection broken in reply");
  1216. }
  1217.  
  1218. /* Mail Access Protocol parse reply
  1219.  * Accepts: MAIL stream
  1220.  *        text of reply
  1221.  * Returns: parsed reply, or NIL if can't parse at least a tag and key
  1222.  */
  1223.  
  1224.  
  1225. IMAPPARSEDREPLY *imap_parse_reply (stream,text)
  1226.     MAILSTREAM *stream;
  1227.     char *text;
  1228. {
  1229.   if (LOCAL->reply.line) fs_give ((void **) &LOCAL->reply.line);
  1230.   if (!(LOCAL->reply.line = text)) {
  1231.                 /* NIL text means the stream died */
  1232.     tcp_close (LOCAL->tcpstream);
  1233.     LOCAL->tcpstream = NIL;
  1234.     return NIL;
  1235.   }
  1236.   if (stream->debug) mm_dlog (LOCAL->reply.line);
  1237.   LOCAL->reply.key = NIL;    /* init fields in case error */
  1238.   LOCAL->reply.text = NIL;
  1239.                 /* parse separate tag, key, text */
  1240.   if (!((LOCAL->reply.tag = (char *) strtok (LOCAL->reply.line," ")) &&
  1241.     (LOCAL->reply.key = (char *) strtok (NIL," ")))) {
  1242.                 /* determine what is missing */
  1243.     if (!LOCAL->reply.tag) strcpy (LOCAL->tmp,"IMAP server sent a blank line");
  1244.     else sprintf (LOCAL->tmp,"Missing IMAP reply key: %.80s",LOCAL->reply.tag);
  1245.     mm_log (LOCAL->tmp,WARN);    /* pass up the barfage */
  1246.     return NIL;            /* can't parse this text */
  1247.   }
  1248.   ucase (LOCAL->reply.key);    /* make sure key is upper case */
  1249.                 /* get text as well, allow empty text */
  1250.   if (!(LOCAL->reply.text = (char *) strtok (NIL,"\n")))
  1251.     LOCAL->reply.text = LOCAL->reply.key + strlen (LOCAL->reply.key);
  1252.   return &LOCAL->reply;        /* return parsed reply */
  1253. }
  1254.  
  1255. /* Mail Access Protocol fake reply
  1256.  * Accepts: MAIL stream
  1257.  *        tag
  1258.  *        text of fake reply
  1259.  * Returns: parsed reply
  1260.  */
  1261.  
  1262. IMAPPARSEDREPLY *imap_fake (stream,tag,text)
  1263.     MAILSTREAM *stream;
  1264.     char *tag;
  1265.     char *text;
  1266. {
  1267.                 /* build fake reply string */
  1268.   sprintf (LOCAL->tmp,"%s %s",tag,text);
  1269.                 /* parse and return it */
  1270.   return imap_parse_reply (stream,cpystr (LOCAL->tmp));
  1271. }
  1272.  
  1273.  
  1274. /* Mail Access Protocol check for OK response in tagged reply
  1275.  * Accepts: MAIL stream
  1276.  *        parsed reply
  1277.  * Returns: T if OK else NIL
  1278.  */
  1279.  
  1280. long imap_OK (stream,reply)
  1281.     MAILSTREAM *stream;
  1282.     IMAPPARSEDREPLY *reply;
  1283. {
  1284.                 /* OK - operation succeeded */
  1285.   if (!strcmp (reply->key,"OK") ||
  1286.       (!strcmp (reply->tag,"*") && !strcmp (reply->key,"PREAUTH")))
  1287.     return T;
  1288.                 /* NO - operation failed */
  1289.   else if (strcmp (reply->key,"NO")) {
  1290.                 /* BAD - operation rejected */
  1291.     if (!strcmp (reply->key,"BAD"))
  1292.       sprintf (LOCAL->tmp,"IMAP error: %.80s",reply->text);
  1293.                 /* BYE - server is going away */
  1294.     else if (!strcmp (reply->key,"BYE")) strcpy (LOCAL->tmp,reply->text);
  1295.     else sprintf (LOCAL->tmp,"Unexpected IMAP response: %.80s %.80s",
  1296.           reply->key,reply->text);
  1297.     mm_log (LOCAL->tmp,WARN);    /* log the sucker */
  1298.   }
  1299.   return NIL;
  1300. }
  1301.  
  1302. /* Mail Access Protocol parse and act upon unsolicited reply
  1303.  * Accepts: MAIL stream
  1304.  *        parsed reply
  1305.  */
  1306.  
  1307. void imap_parse_unsolicited (stream,reply)
  1308.     MAILSTREAM *stream;
  1309.     IMAPPARSEDREPLY *reply;
  1310. {
  1311.   long msgno;
  1312.   char *s;
  1313.   char *keyptr,*txtptr;
  1314.                 /* see if key is a number */
  1315.   msgno = strtol (reply->key,&s,10);
  1316.   if (*s) {            /* if non-numeric */
  1317.     if (!strcmp (reply->key,"FLAGS")) imap_parse_flaglst (stream,reply);
  1318.     else if (!strcmp (reply->key,"SEARCH")) imap_searched (stream,reply->text);
  1319.     else if (!strcmp (reply->key,"MAILBOX")) {
  1320.       sprintf (LOCAL->tmp,"%s%s",LOCAL->prefix ? LOCAL->prefix:"",reply->text);
  1321.       mm_mailbox (LOCAL->tmp);
  1322.     }
  1323.     else if (!strcmp (reply->key,"BBOARD")) {
  1324.       sprintf (LOCAL->tmp,"%s%s",LOCAL->prefix ? LOCAL->prefix:"",reply->text);
  1325.       mm_bboard (LOCAL->tmp);
  1326.     }
  1327.     else if (!strcmp (reply->key,"BYE")) {
  1328.       if (!stream->silent) mm_log (reply->text,(long) NIL);
  1329.     }
  1330.     else if (!strcmp (reply->key,"OK") || !strcmp (reply->key,"PREAUTH")) {
  1331.                 /* note if server said it was readonly */
  1332.       strncpy (LOCAL->tmp,reply->text,11);
  1333.       LOCAL->tmp[11] = '\0';    /* tie off text */
  1334.       if (strcmp (ucase (LOCAL->tmp),"[READ-ONLY]")) s = reply->text;
  1335.       else {
  1336.     stream->readonly = T;    /* make readonly now */
  1337.     s = reply->text + 12;    /* skip the cookie */
  1338.       }
  1339.       mm_notify (stream,s,(long) NIL);
  1340.     }
  1341.     else if (!strcmp (reply->key,"NO")) {
  1342.       if (!stream->silent) mm_notify (stream,reply->text,WARN);
  1343.     }
  1344.     else if (!strcmp (reply->key,"BAD")) mm_notify (stream,reply->text,ERROR);
  1345.     else {
  1346.       sprintf (LOCAL->tmp,"Unexpected unsolicited message: %.80s",reply->key);
  1347.       mm_log (LOCAL->tmp,WARN);
  1348.     }
  1349.   }
  1350.  
  1351.   else {            /* if numeric, a keyword follows */
  1352.                 /* deposit null at end of keyword */
  1353.     keyptr = ucase ((char *) strtok (reply->text," "));
  1354.                 /* and locate the text after it */
  1355.     txtptr = (char *) strtok (NIL,"\n");
  1356.                 /* now take the action */
  1357.                 /* change in size of mailbox */
  1358.     if (!strcmp (keyptr,"EXISTS")) mail_exists (stream,msgno);
  1359.     else if (!strcmp (keyptr,"RECENT")) mail_recent (stream,msgno);
  1360.     else if (!strcmp (keyptr,"EXPUNGE")) imap_expunged (stream,msgno);
  1361.     else if (!strcmp (keyptr,"FETCH"))
  1362.       imap_parse_data (stream,msgno,txtptr,reply);
  1363.                 /* obsolete alias for FETCH */
  1364.     else if (!strcmp (keyptr,"STORE"))
  1365.       imap_parse_data (stream,msgno,txtptr,reply);
  1366.                 /* obsolete response to COPY */
  1367.     else if (strcmp (keyptr,"COPY")) {
  1368.       sprintf (LOCAL->tmp,"Unknown message data: %ld %.80s",msgno,keyptr);
  1369.       mm_log (LOCAL->tmp,WARN);
  1370.     }
  1371.   }
  1372. }
  1373.  
  1374. /* Mail Access Protocol parse flag list
  1375.  * Accepts: MAIL stream
  1376.  *        parsed reply
  1377.  *
  1378.  *  The reply->line is yanked out of the parsed reply and stored on
  1379.  * stream->flagstring.  This is the original fs_get'd reply string, and
  1380.  * has all the flagstrings embedded in it.
  1381.  */
  1382.  
  1383. void imap_parse_flaglst (stream,reply)
  1384.     MAILSTREAM *stream;
  1385.     IMAPPARSEDREPLY *reply;
  1386. {
  1387.   char *text = reply->text;
  1388.   char *flag;
  1389.   long i;
  1390.                 /* flush old flagstring and flags if any */
  1391.   if (stream->flagstring) fs_give ((void **) &stream->flagstring);
  1392.   for (i = 0; i < NUSERFLAGS; ++i) stream->user_flags[i] = NIL;
  1393.                 /* remember this new one */
  1394.   stream->flagstring = reply->line;
  1395.   reply->line = NIL;
  1396.   ++text;            /* skip past open parenthesis */
  1397.                 /* get first flag if any */
  1398.   if (flag = (char *) strtok (text," )")) {
  1399.     i = 0;            /* init flag index */
  1400.                 /* add all user flags */
  1401.     do if (*flag != '\\') stream->user_flags[i++] = flag;
  1402.       while (flag = (char *) strtok (NIL," )"));
  1403.   }
  1404. }
  1405.  
  1406.  
  1407. /* Mail Access Protocol messages have been searched out
  1408.  * Accepts: MAIL stream
  1409.  *        list of message numbers
  1410.  *
  1411.  * Calls external "mail_searched" function to notify main program
  1412.  */
  1413.  
  1414. void imap_searched (stream,text)
  1415.     MAILSTREAM *stream;
  1416.     char *text;
  1417. {
  1418.                 /* only do something if have text */
  1419.   if (text && (text = (char *) strtok (text," ")))
  1420.     for (; text; text = (char *) strtok (NIL," "))
  1421.       mail_searched (stream,atol (text));
  1422. }
  1423.  
  1424. /* Mail Access Protocol message has been expunged
  1425.  * Accepts: MAIL stream
  1426.  *        message number
  1427.  *
  1428.  * Calls external "mail_searched" function to notify main program
  1429.  */
  1430.  
  1431. void imap_expunged (stream,msgno)
  1432.     MAILSTREAM *stream;
  1433.     long msgno;
  1434. {
  1435.   MESSAGECACHE *elt = (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_ELT);
  1436.   if (elt) {
  1437.     if (elt->data1) fs_give ((void **) &elt->data1);
  1438.     if (elt->data2) fs_give ((void **) &elt->data2);
  1439.   }
  1440.   mail_expunged (stream,msgno);    /* notify upper level */
  1441. }
  1442.  
  1443.  
  1444. /* Mail Access Protocol parse data
  1445.  * Accepts: MAIL stream
  1446.  *        message #
  1447.  *        text to parse
  1448.  *        parsed reply
  1449.  *
  1450.  *  This code should probably be made a bit more paranoid about malformed
  1451.  * S-expressions.
  1452.  */
  1453.  
  1454. void imap_parse_data (stream,msgno,text,reply)
  1455.     MAILSTREAM *stream;
  1456.     long msgno;
  1457.     char *text;
  1458.                    IMAPPARSEDREPLY *reply;
  1459. {
  1460.   char *prop;
  1461.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1462.   ++text;            /* skip past open parenthesis */
  1463.                 /* parse Lisp-form property list */
  1464.   while (prop = (char *) strtok (text," )")) {
  1465.                 /* point at value */
  1466.     text = (char *) strtok (NIL,"\n");
  1467.                 /* parse the property and its value */
  1468.     imap_parse_prop (stream,elt,ucase (prop),&text,reply);
  1469.   }
  1470. }
  1471.  
  1472. /* Mail Access Protocol parse property
  1473.  * Accepts: MAIL stream
  1474.  *        cache item
  1475.  *        property name
  1476.  *        property value text pointer
  1477.  *        parsed reply
  1478.  */
  1479.  
  1480. void imap_parse_prop (stream,elt,prop,txtptr,reply)
  1481.     MAILSTREAM *stream;
  1482.     MESSAGECACHE *elt;
  1483.     char *prop;
  1484.                    char **txtptr;
  1485.     IMAPPARSEDREPLY *reply;
  1486. {
  1487.   char *s;
  1488.   ENVELOPE **env;
  1489.   BODY **body;
  1490.   long i = elt->msgno - 1;
  1491.   if (!strcmp (prop,"ENVELOPE")) {
  1492.     if (stream->scache) {    /* short cache, flush old stuff */
  1493.       mail_free_envelope (&stream->env);
  1494.       mail_free_body (&stream->body);
  1495.       stream->msgno =elt->msgno;/* set new current message number */
  1496.       env = &stream->env;    /* get pointer to envelope */
  1497.     }
  1498.     else env = &mail_lelt (stream,elt->msgno)->env;
  1499.     imap_parse_envelope (stream,env,txtptr,reply);
  1500.   }
  1501.   else if (!strcmp (prop,"FLAGS")) imap_parse_flags (stream,elt,txtptr);
  1502.   else if (!strcmp (prop,"INTERNALDATE")) {
  1503.     if (s = imap_parse_string (stream,txtptr,reply,(long) NIL)) {
  1504.       if (!mail_parse_date (elt,s)) {
  1505.     sprintf (LOCAL->tmp,"Bogus date: %.80s",s);
  1506.     mm_log (LOCAL->tmp,WARN);
  1507.       }
  1508.       fs_give ((void **) &s);
  1509.     }
  1510.   }
  1511.   else if (!strcmp (prop,"RFC822.HEADER")) {
  1512.     if (elt->data1) fs_give ((void **) &elt->data1);
  1513.     elt->data1 = (unsigned long) imap_parse_string (stream,txtptr,reply,
  1514.                             elt->msgno);
  1515.   }
  1516.  
  1517.   else if (!strcmp (prop,"RFC822.SIZE"))
  1518.     elt->rfc822_size = imap_parse_number (stream,txtptr);
  1519.   else if (!strcmp (prop,"RFC822.TEXT")) {
  1520.     if (elt->data2) fs_give ((void **) &elt->data2);
  1521.     elt->data2 = (unsigned long) imap_parse_string (stream,txtptr,reply,
  1522.                             elt->msgno);
  1523.   }
  1524.   else if (prop[0] == 'B' && prop[1] == 'O' && prop[2] == 'D' &&
  1525.        prop[3] == 'Y') {
  1526.     s = cpystr (prop+4);    /* copy segment specifier */
  1527.     if (stream->scache) {    /* short cache, flush old stuff */
  1528.       if (elt->msgno != stream->msgno) {
  1529.                 /* losing real bad here */
  1530.     mail_free_envelope (&stream->env);
  1531.     mail_free_body (&stream->body);
  1532.     sprintf (LOCAL->tmp,"Body received for %ld when current is %ld",
  1533.          elt->msgno,stream->msgno);
  1534.     mm_log (LOCAL->tmp,WARN);
  1535.     stream->msgno = elt->msgno;
  1536.       }
  1537.       body = &stream->body;    /* get pointer to body */
  1538.     }
  1539.     else body = &mail_lelt (stream,elt->msgno)->body;
  1540.     imap_parse_body (stream,elt->msgno,body,s,txtptr,reply);
  1541.     fs_give ((void **) &s);
  1542.   }
  1543.                 /* this shouldn't happen with our client */
  1544.   else if (!strcmp (prop,"RFC822")) {
  1545.     if (elt->data2) fs_give ((void **) &elt->data2);
  1546.     elt->data2 = (unsigned long) imap_parse_string (stream,txtptr,reply,
  1547.                             elt->msgno);
  1548.   }
  1549.   else {
  1550.     sprintf (LOCAL->tmp,"Unknown message property: %.80s",prop);
  1551.     mm_log (LOCAL->tmp,WARN);
  1552.   }
  1553. }
  1554.  
  1555. /* Mail Access Protocol parse envelope
  1556.  * Accepts: MAIL stream
  1557.  *        pointer to envelope pointer
  1558.  *        current text pointer
  1559.  *        parsed reply
  1560.  *
  1561.  * Updates text pointer
  1562.  */
  1563.  
  1564. void imap_parse_envelope (stream,env,txtptr,reply)
  1565.     MAILSTREAM *stream;
  1566.     ENVELOPE **env;
  1567.     char **txtptr;
  1568.                    IMAPPARSEDREPLY *reply;
  1569. {
  1570.   char c = *((*txtptr)++);    /* grab first character */
  1571.                 /* ignore leading spaces */
  1572.   while (c == ' ') c = *((*txtptr)++);
  1573.                 /* free any old envelope */
  1574.   if (*env) mail_free_envelope (env);
  1575.   switch (c) {            /* dispatch on first character */
  1576.   case '(':            /* if envelope S-expression */
  1577.     *env = mail_newenvelope ();    /* parse the new envelope */
  1578.     (*env)->date = imap_parse_string (stream,txtptr,reply,(long) NIL);
  1579.     (*env)->subject = imap_parse_string (stream,txtptr,reply,(long) NIL);
  1580.     (*env)->from = imap_parse_adrlist (stream,txtptr,reply);
  1581.     (*env)->sender = imap_parse_adrlist (stream,txtptr,reply);
  1582.     (*env)->reply_to = imap_parse_adrlist (stream,txtptr,reply);
  1583.     (*env)->to = imap_parse_adrlist (stream,txtptr,reply);
  1584.     (*env)->cc = imap_parse_adrlist (stream,txtptr,reply);
  1585.     (*env)->bcc = imap_parse_adrlist (stream,txtptr,reply);
  1586.     (*env)->in_reply_to = imap_parse_string (stream,txtptr,reply,(long) NIL);
  1587.     (*env)->message_id = imap_parse_string (stream,txtptr,reply,(long) NIL);
  1588.     if (**txtptr != ')') {
  1589.       sprintf (LOCAL->tmp,"Junk at end of envelope: %.80s",*txtptr);
  1590.       mm_log (LOCAL->tmp,WARN);
  1591.     }
  1592.     else ++*txtptr;        /* skip past delimiter */
  1593.     break;
  1594.   case 'N':            /* if NIL */
  1595.   case 'n':
  1596.     ++*txtptr;            /* bump past "I" */
  1597.     ++*txtptr;            /* bump past "L" */
  1598.     break;
  1599.   default:
  1600.     sprintf (LOCAL->tmp,"Not an envelope: %.80s",*txtptr);
  1601.     mm_log (LOCAL->tmp,WARN);
  1602.     break;
  1603.   }
  1604. }
  1605.  
  1606. /* Mail Access Protocol parse address list
  1607.  * Accepts: MAIL stream
  1608.  *        current text pointer
  1609.  *        parsed reply
  1610.  * Returns: address list, NIL on failure
  1611.  *
  1612.  * Updates text pointer
  1613.  */
  1614.  
  1615. ADDRESS *imap_parse_adrlist (stream,txtptr,reply)
  1616.     MAILSTREAM *stream;
  1617.     char **txtptr;
  1618.                       IMAPPARSEDREPLY *reply;
  1619. {
  1620.   ADDRESS *adr = NIL;
  1621.   char c = **txtptr;        /* sniff at first character */
  1622.                 /* ignore leading spaces */
  1623.   while (c == ' ') c = *++*txtptr;
  1624.   ++*txtptr;            /* skip past open paren */
  1625.   switch (c) {
  1626.   case '(':            /* if envelope S-expression */
  1627.     adr = imap_parse_address (stream,txtptr,reply);
  1628.     if (**txtptr != ')') {
  1629.       sprintf (LOCAL->tmp,"Junk at end of address list: %.80s",*txtptr);
  1630.       mm_log (LOCAL->tmp,WARN);
  1631.     }
  1632.     else ++*txtptr;        /* skip past delimiter */
  1633.     break;
  1634.   case 'N':            /* if NIL */
  1635.   case 'n':
  1636.     ++*txtptr;            /* bump past "I" */
  1637.     ++*txtptr;            /* bump past "L" */
  1638.     break;
  1639.   default:
  1640.     sprintf (LOCAL->tmp,"Not an address: %.80s",*txtptr);
  1641.     mm_log (LOCAL->tmp,WARN);
  1642.     break;
  1643.   }
  1644.   return adr;
  1645. }
  1646.  
  1647. /* Mail Access Protocol parse address
  1648.  * Accepts: MAIL stream
  1649.  *        current text pointer
  1650.  *        parsed reply
  1651.  * Returns: address, NIL on failure
  1652.  *
  1653.  * Updates text pointer
  1654.  */
  1655.  
  1656. ADDRESS *imap_parse_address (stream,txtptr,reply)
  1657.     MAILSTREAM *stream;
  1658.     char **txtptr;
  1659.                       IMAPPARSEDREPLY *reply;
  1660. {
  1661.   ADDRESS *adr = NIL;
  1662.   ADDRESS *ret = NIL;
  1663.   ADDRESS *prev = NIL;
  1664.   char c = **txtptr;        /* sniff at first address character */
  1665.   switch (c) {
  1666.   case '(':            /* if envelope S-expression */
  1667.     while (c == '(') {        /* recursion dies on small stack machines */
  1668.       ++*txtptr;        /* skip past open paren */
  1669.       if (adr) prev = adr;    /* note previous if any */
  1670.       adr = mail_newaddr ();    /* instantiate address and parse its fields */
  1671.       adr->personal = imap_parse_string (stream,txtptr,reply,(long) NIL);
  1672.       adr->adl = imap_parse_string (stream,txtptr,reply,(long) NIL);
  1673.       adr->mailbox = imap_parse_string (stream,txtptr,reply,(long) NIL);
  1674.       adr->host = imap_parse_string (stream,txtptr,reply,(long) NIL);
  1675.       if (**txtptr != ')') {    /* handle trailing paren */
  1676.     sprintf (LOCAL->tmp,"Junk at end of address: %.80s",*txtptr);
  1677.     mm_log (LOCAL->tmp,WARN);
  1678.       }
  1679.       else ++*txtptr;        /* skip past close paren */
  1680.       c = **txtptr;        /* set up for while test */
  1681.                 /* ignore leading spaces in front of next */
  1682.       while (c == ' ') c = *++*txtptr;
  1683.       if (!ret) ret = adr;    /* if first time note first adr */
  1684.                 /* if previous link new block to it */
  1685.       if (prev) prev->next = adr;
  1686.     }
  1687.     break;
  1688.  
  1689.   case 'N':            /* if NIL */
  1690.   case 'n':
  1691.     *txtptr += 3;        /* bump past NIL */
  1692.     break;
  1693.   default:
  1694.     sprintf (LOCAL->tmp,"Not an address: %.80s",*txtptr);
  1695.     mm_log (LOCAL->tmp,WARN);
  1696.     break;
  1697.   }
  1698.   return ret;
  1699. }
  1700.  
  1701. /* Mail Access Protocol parse flags
  1702.  * Accepts: current message cache
  1703.  *        current text pointer
  1704.  *
  1705.  * Updates text pointer
  1706.  */
  1707.  
  1708. void imap_parse_flags (stream,elt,txtptr)
  1709.     MAILSTREAM *stream;
  1710.     MESSAGECACHE *elt;
  1711.     char **txtptr;
  1712. {
  1713.   char *flag;
  1714.   char c;
  1715.   elt->user_flags = NIL;    /* zap old flag values */
  1716.   elt->seen = elt->deleted = elt->flagged = elt->answered = elt->recent = NIL;
  1717.   while (T) {            /* parse list of flags */
  1718.     flag = ++*txtptr;        /* point at a flag */
  1719.                 /* scan for end of flag */
  1720.     while (**txtptr != ' ' && **txtptr != ')') ++*txtptr;
  1721.     c = **txtptr;        /* save delimiter */
  1722.     **txtptr = '\0';        /* tie off flag */
  1723.     if (*flag != '\0') {    /* if flag is non-null */
  1724.       if (*flag == '\\') {    /* if starts with \ must be sys flag */
  1725.     if (!strcmp (ucase (flag),"\\SEEN")) elt->seen = T;
  1726.     else if (!strcmp (flag,"\\DELETED")) elt->deleted = T;
  1727.     else if (!strcmp (flag,"\\FLAGGED")) elt->flagged = T;
  1728.     else if (!strcmp (flag,"\\ANSWERED")) elt->answered = T;
  1729.     else if (!strcmp (flag,"\\RECENT")) elt->recent = T;
  1730.                 /* coddle TOPS-20 server */
  1731.     else if (strcmp (flag,"\\XXXX") && strcmp (flag,"\\YYYY") &&
  1732.          strncmp (flag,"\\UNDEFINEDFLAG",14)) {
  1733.       sprintf (LOCAL->tmp,"Unknown system flag: %.80s",flag);
  1734.       mm_log (LOCAL->tmp,WARN);
  1735.     }
  1736.       }
  1737.                 /* otherwise user flag */
  1738.       else imap_parse_user_flag (stream,elt,flag);
  1739.     }
  1740.     if (c == ')') break;    /* quit if end of list */
  1741.   }
  1742.   ++*txtptr;            /* bump past delimiter */
  1743. }
  1744.  
  1745. /* Mail Access Protocol parse user flag
  1746.  * Accepts: message cache element
  1747.  *        flag name
  1748.  */
  1749.  
  1750. void imap_parse_user_flag (stream,elt,flag)
  1751.     MAILSTREAM *stream;
  1752.     MESSAGECACHE *elt;
  1753.     char *flag;
  1754. {
  1755.   long i;
  1756.                   /* sniff through all user flags */
  1757.   for (i = 0; i < NUSERFLAGS; ++i)
  1758.                   /* match this one? */
  1759.     if (!strcmp (flag,stream->user_flags[i])) {
  1760.       elt->user_flags |= 1 << i;/* yes, set the bit for that flag */
  1761.       return;            /* and quit */
  1762.     }
  1763.   sprintf (LOCAL->tmp,"Unknown user flag: %.80s",flag);
  1764.   mm_log (LOCAL->tmp,WARN);
  1765. }
  1766.  
  1767. /* Mail Access Protocol parse string
  1768.  * Accepts: MAIL stream
  1769.  *        current text pointer
  1770.  *        parsed reply
  1771.  *        flag that it may be kept outside of free storage cache
  1772.  * Returns: string
  1773.  *
  1774.  * Updates text pointer
  1775.  */
  1776.  
  1777. char *imap_parse_string (stream,txtptr,reply,special)
  1778.     MAILSTREAM *stream;
  1779.     char **txtptr;
  1780.                   IMAPPARSEDREPLY *reply;
  1781.     long special;
  1782. {
  1783.   char *st;
  1784.   char *string = NIL;
  1785.   unsigned long i;
  1786.   char c = **txtptr;        /* sniff at first character */
  1787.                 /* ignore leading spaces */
  1788.   while (c == ' ') c = *++*txtptr;
  1789.   st = ++*txtptr;        /* remember start of string */
  1790.   switch (c) {
  1791.   case '"':            /* if quoted string */
  1792.     i = 1;            /* initial byte count */
  1793.     while (**txtptr != '"') {    /* search for end of string */
  1794.       ++i;            /* bump count */
  1795.       ++*txtptr;        /* bump pointer */
  1796.     }
  1797.     **txtptr = '\0';        /* tie off string */
  1798.     string = (char *) fs_get (i);
  1799.     strncpy (string,st,i);    /* copy the string */
  1800.     ++*txtptr;            /* bump past delimiter */
  1801.     break;
  1802.   case 'N':            /* if NIL */
  1803.   case 'n':
  1804.     ++*txtptr;            /* bump past "I" */
  1805.     ++*txtptr;            /* bump past "L" */
  1806.     break;
  1807.  
  1808.   case '{':            /* if literal string */
  1809.                 /* get size of string */
  1810.     i = imap_parse_number (stream,txtptr);
  1811.     if (special && mailgets)    /* have special routine to slurp string? */
  1812.       string = (*mailgets) (tcp_getbuffer,LOCAL->tcpstream,i);
  1813.     else {            /* must slurp into free storage */
  1814.       string = (char *) fs_get (i + 1);
  1815.       *string = '\0';        /* init in case getbuffer fails */
  1816.                 /* get the literal */
  1817.       tcp_getbuffer (LOCAL->tcpstream,i,string);
  1818.     }
  1819.     fs_give ((void **) &reply->line);
  1820.                 /* get new reply text line */
  1821.     reply->line = tcp_getline (LOCAL->tcpstream);
  1822.     if (stream->debug) mm_dlog (reply->line);
  1823.     *txtptr = reply->line;    /* set text pointer to point at it */
  1824.     break;
  1825.   default:
  1826.     sprintf (LOCAL->tmp,"Not a string: %c%.80s",c,*txtptr);
  1827.     mm_log (LOCAL->tmp,WARN);
  1828.     break;
  1829.   }
  1830.   return string;
  1831. }
  1832.  
  1833.  
  1834. /* Mail Access Protocol parse number
  1835.  * Accepts: MAIL stream
  1836.  *        current text pointer
  1837.  * Returns: number parsed
  1838.  *
  1839.  * Updates text pointer
  1840.  */
  1841.  
  1842. unsigned long imap_parse_number (stream,txtptr)
  1843.     MAILSTREAM *stream;
  1844.     char **txtptr;
  1845. {                /* parse number */
  1846.   long i = strtol (*txtptr,txtptr,10);
  1847.   if (i < 0) {            /* number valid? */
  1848.     sprintf (LOCAL->tmp,"Bad number: %ld",i);
  1849.     mm_log (LOCAL->tmp,WARN);
  1850.     i = 0;            /* make sure valid */
  1851.   }
  1852.   return (unsigned long) i;
  1853. }
  1854.  
  1855. /* Mail Access Protocol parse body structure or contents
  1856.  * Accepts: MAIL stream
  1857.  *        pointer to body pointer
  1858.  *        pointer to segment
  1859.  *        current text pointer
  1860.  *        parsed reply
  1861.  *
  1862.  * Updates text pointer, stores body
  1863.  */
  1864.  
  1865. void imap_parse_body (stream,msgno,body,seg,txtptr,reply)
  1866.     MAILSTREAM *stream;
  1867.     long msgno;
  1868.     BODY **body;
  1869.     char *seg;
  1870.                    char **txtptr;
  1871.     IMAPPARSEDREPLY *reply;
  1872. {
  1873.   char *s;
  1874.   unsigned long i;
  1875.   BODY *b;
  1876.   PART *part;
  1877.   switch (*seg++) {        /* dispatch based on type of data */
  1878.   case '\0':            /* body structure */
  1879.     mail_free_body (body);    /* flush any prior body */
  1880.                 /* instantiate and parse a new body */
  1881.     imap_parse_body_structure (stream,*body = mail_newbody (),txtptr,reply);
  1882.     break;
  1883.   case '[':            /* body section text */
  1884.     if ((!(s = strchr (seg,']'))) || s[1]) {
  1885.       sprintf (LOCAL->tmp,"Bad body index: %.80s",seg);
  1886.       mm_log (LOCAL->tmp,WARN);
  1887.       return;
  1888.     }
  1889.     *s = '\0';            /* tie off section specifier */
  1890.                 /* get the body section text */
  1891.     s = imap_parse_string (stream,txtptr,reply,msgno);
  1892.     if (!(b = *body)) {        /* must have structure first */
  1893.       mm_log ("Body contents received when body structure unknown",WARN);
  1894.       fs_give ((void **) &s);
  1895.       return;
  1896.     }
  1897.                 /* get first section number */
  1898.     if (!(seg && *seg && ((i = strtol (seg,&seg,10)) > 0))) {
  1899.       mm_log ("Bogus section number",WARN);
  1900.       fs_give ((void **) &s);
  1901.       return;
  1902.     }
  1903.  
  1904.     do {            /* multipart content? */
  1905.       if (b->type == TYPEMULTIPART) {
  1906.     part = b->contents.part;/* yes, find desired part */
  1907.     while (--i && (part = part->next));
  1908.     if (!part || (((b = &part->body)->type == TYPEMULTIPART) && !*s)) {
  1909.       mm_log ("Bad section number",WARN);
  1910.       fs_give ((void **) &s);
  1911.       return;
  1912.     }
  1913.       }
  1914.       else if (i != 1) {    /* otherwise must be section 1 */
  1915.     mm_log ("Invalid section number",WARN);
  1916.     fs_give ((void **) &s);
  1917.     return;
  1918.       }
  1919.                 /* need to go down further? */
  1920.       if (i = *seg) switch (b->type) {
  1921.       case TYPEMESSAGE:        /* embedded message, get body */
  1922.     b = b->contents.msg.body;
  1923.       case TYPEMULTIPART:    /* multipart, get next section */
  1924.     if ((*seg++ == '.') && (i = strtol (seg,&seg,10)) > 0) break;
  1925.       default:            /* bogus subpart */
  1926.     mm_log ("Invalid sub-section",WARN);
  1927.     fs_give ((void **) &s);
  1928.     return;
  1929.       }
  1930.     } while (i);
  1931.     if (b) switch (b->type) {    /* decide where the data goes based on type */
  1932.     case TYPEMULTIPART:        /* nothing to fetch with these */
  1933.       mm_log ("Textual body contents received for MULTIPART body part",WARN);
  1934.       fs_give ((void **) &s);
  1935.       return;
  1936.     case TYPEMESSAGE:        /* encapsulated message */
  1937.       fs_give ((void **) &b->contents.msg.text);
  1938.       b->contents.msg.text = s;
  1939.       break;
  1940.     case TYPETEXT:        /* textual data */
  1941.       fs_give ((void **) &b->contents.text);
  1942.       b->contents.text = (unsigned char *) s;
  1943.       break;
  1944.     default:            /* otherwise assume it is binary */
  1945.       fs_give ((void **) &b->contents.binary);
  1946.       b->contents.binary = (void *) s;
  1947.       break;
  1948.     }
  1949.     break;
  1950.   default:            /* bogon */
  1951.     sprintf (LOCAL->tmp,"Bad body fetch: %.80s",seg);
  1952.     mm_log (LOCAL->tmp,WARN);
  1953.     return;
  1954.   }
  1955. }
  1956.  
  1957. /* Mail Access Protocol parse body structure
  1958.  * Accepts: MAIL stream
  1959.  *        current text pointer
  1960.  *        parsed reply
  1961.  *        body structure to write into
  1962.  *
  1963.  * Updates text pointer
  1964.  */
  1965.  
  1966. void imap_parse_body_structure (stream,body,txtptr,reply)
  1967.     MAILSTREAM *stream;
  1968.     BODY *body;
  1969.     char **txtptr;
  1970.                      IMAPPARSEDREPLY *reply;
  1971. {
  1972.   char *s;
  1973.   PART *part = NIL;
  1974.   PARAMETER *param = NIL;
  1975.   char c = *((*txtptr)++);    /* grab first character */
  1976.                 /* ignore leading spaces */
  1977.   while (c == ' ') c = *((*txtptr)++);
  1978.   switch (c) {            /* dispatch on first character */
  1979.   case '(':            /* body structure list */
  1980.     if (**txtptr == '(') {    /* multipart body? */
  1981.       body->type= TYPEMULTIPART;/* yes, set its type */
  1982.       do {            /* instantiate new body part */
  1983.     if (part) part = part->next = mail_newbody_part ();
  1984.     else body->contents.part = part = mail_newbody_part ();
  1985.                 /* parse it */
  1986.     imap_parse_body_structure (stream,&part->body,txtptr,reply);
  1987.       } while (**txtptr == '(');/* for each body part */
  1988.       if (!(body->subtype = imap_parse_string (stream,txtptr,reply,(long)NIL)))
  1989.     mm_log ("Missing multipart subtype",WARN);
  1990.       if (**txtptr != ')') {    /* validate ending */
  1991.     sprintf (LOCAL->tmp,"Junk at end of multipart body: %.80s",*txtptr);
  1992.     mm_log (LOCAL->tmp,WARN);
  1993.       }
  1994.       else ++*txtptr;        /* skip past delimiter */
  1995.     }
  1996.  
  1997.     else {            /* not multipart, parse type name */
  1998.       if (**txtptr == ')') {    /* empty body? */
  1999.     ++*txtptr;        /* bump past it */
  2000.     break;            /* and punt */
  2001.       }
  2002.       body->type = TYPEOTHER;    /* assume unknown type */
  2003.       body->encoding = ENCOTHER;/* and unknown encoding */
  2004.                 /* parse type */
  2005.       if (s = imap_parse_string (stream,txtptr,reply,(long) NIL)) {
  2006.     ucase (s);        /* make parse easier */
  2007.     switch (*s) {        /* dispatch based on type */
  2008.     case 'A':        /* APPLICATION or AUDIO */
  2009.       if (!strcmp (s+1,"PPLICATION")) body->type = TYPEAPPLICATION;
  2010.       else if (!strcmp (s+1,"UDIO")) body->type = TYPEAUDIO;
  2011.       break;
  2012.     case 'I':        /* IMAGE */
  2013.       if (!strcmp (s+1,"MAGE")) body->type = TYPEIMAGE;
  2014.       break;
  2015.     case 'M':        /* MESSAGE */
  2016.       if (!strcmp (s+1,"ESSAGE")) body->type = TYPEMESSAGE;
  2017.       break;
  2018.     case 'T':        /* TEXT */
  2019.       if (!strcmp (s+1,"EXT")) body->type = TYPETEXT;
  2020.       break;
  2021.     case 'V':        /* VIDEO */
  2022.       if (!strcmp (s+1,"IDEO")) body->type = TYPEVIDEO;
  2023.       break;
  2024.     default:
  2025.       break;
  2026.     }
  2027.     fs_give ((void **) &s);    /* flush the string */
  2028.       }
  2029.                 /* parse subtype */
  2030.       body->subtype = imap_parse_string (stream,txtptr,reply,(long) NIL);
  2031.  
  2032.       body->parameter = NIL;    /* init parameter list */
  2033.  
  2034.       c = *(*txtptr)++;        /* sniff at first character */
  2035.                 /* ignore leading spaces */
  2036.       while (c == ' ') c = *(*txtptr)++;
  2037.                 /* parse parameter list */
  2038.       if (c == '(') while (c != ')') {
  2039.     if (body->parameter)    /* append new parameter to tail */
  2040.       param = param->next = mail_newbody_parameter ();
  2041.     else body->parameter = param = mail_newbody_parameter ();
  2042.     if (!(param->attribute = imap_parse_string (stream,txtptr,reply,
  2043.                             (long) NIL))){
  2044.       mm_log ("Missing parameter attribute",WARN);
  2045.       break;
  2046.     }
  2047.     if (!(param->value = imap_parse_string (stream,txtptr,reply,
  2048.                         (long) NIL))) {
  2049.       sprintf (LOCAL->tmp,"Missing value for parameter %.80s",
  2050.            param->attribute);
  2051.       mm_log (LOCAL->tmp,WARN);
  2052.       break;
  2053.     }
  2054.     switch (c = **txtptr) {    /* see what comes after */
  2055.     case ' ':        /* flush whitespace */
  2056.       while ((c = *++*txtptr) == ' ');
  2057.       break;
  2058.     case ')':        /* end of attribute/value pairs */
  2059.       ++*txtptr;        /* skip past closing paren */
  2060.       break;
  2061.     default:
  2062.       sprintf (LOCAL->tmp,"Junk at end of parameter: %.80s",s);
  2063.       mm_log (LOCAL->tmp,WARN);
  2064.       break;
  2065.     }
  2066.       }
  2067.       else {            /* empty parameter, must be NIL */
  2068.     if (((c == 'N') || (c == 'n')) &&
  2069.         ((*(s = *txtptr) == 'I') || (*s == 'i')) &&
  2070.         ((s[1] == 'L') || (s[1] == 'l')) && (s[2] == ' ')) *txtptr += 2;
  2071.     else {
  2072.       sprintf (LOCAL->tmp,"Bogus body parameter: %c%.80s",c,s);
  2073.       mm_log (LOCAL->tmp,WARN);
  2074.       break;
  2075.     }
  2076.       }
  2077.  
  2078.       body->id = imap_parse_string (stream,txtptr,reply,(long) NIL);
  2079.       body->description = imap_parse_string (stream,txtptr,reply,(long) NIL);
  2080.       if (s = imap_parse_string (stream,txtptr,reply,(long) NIL)) {
  2081.     ucase (s);        /* make parse easier */
  2082.     switch (*s) {        /* dispatch based on encoding */
  2083.     case '7':        /* 7BIT */
  2084.       if (!strcmp (s+1,"BIT")) body->encoding = ENC7BIT;
  2085.       break;
  2086.     case '8':        /* 8BIT */
  2087.       if (!strcmp (s+1,"BIT")) body->encoding = ENC8BIT;
  2088.       break;
  2089.     case 'B':        /* BASE64 or BINARY */
  2090.       if (!strcmp (s+1,"ASE64")) body->encoding = ENCBASE64;
  2091.       else if (!strcmp (s,"INARY")) body->encoding = ENCBINARY;
  2092.       break;
  2093.     case 'Q':        /* QUOTED-PRINTABLE */
  2094.       if (!strcmp (s+1,"UOTED-PRINTABLE"))
  2095.         body->encoding = ENCQUOTEDPRINTABLE;
  2096.       break;
  2097.     default:
  2098.       break;
  2099.     }
  2100.     fs_give ((void **) &s);    /* flush the string */
  2101.       }
  2102.                 /* parse size of contents in bytes */
  2103.       body->size.bytes = imap_parse_number (stream,txtptr);
  2104.       switch (body->type) {    /* possible extra stuff */
  2105.       case TYPEMESSAGE:        /* message envelope and body */
  2106.     if (strcmp (body->subtype,"RFC822")) break;
  2107.     imap_parse_envelope (stream,&body->contents.msg.env,txtptr,reply);
  2108.     body->contents.msg.body = mail_newbody ();
  2109.     imap_parse_body_structure(stream,body->contents.msg.body,txtptr,reply);
  2110.                 /* drop into text case */
  2111.       case TYPETEXT:        /* size in lines */
  2112.     body->size.lines = imap_parse_number (stream,txtptr);
  2113.     break;
  2114.       default:            /* otherwise nothing special */
  2115.     break;
  2116.       }
  2117.       if (**txtptr != ')') {    /* validate ending */
  2118.     sprintf (LOCAL->tmp,"Junk at end of body part: %.80s",*txtptr);
  2119.     mm_log (LOCAL->tmp,WARN);
  2120.       }
  2121.       else ++*txtptr;        /* skip past delimiter */
  2122.     }
  2123.     break;
  2124.  
  2125.   case 'N':            /* if NIL */
  2126.   case 'n':
  2127.     ++*txtptr;            /* bump past "I" */
  2128.     ++*txtptr;            /* bump past "L" */
  2129.     break;
  2130.   default:            /* otherwise quite bogus */
  2131.     sprintf (LOCAL->tmp,"Bogus body structure: %.80s",*txtptr);
  2132.     mm_log (LOCAL->tmp,WARN);
  2133.     break;
  2134.   }
  2135. }
  2136.